package com.huaxinkaiye.utils;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.util.EntityUtils;

import java.io.IOException;

/**
 * Created by imac on 15/2/12.
 */
public class HttpGetUtil {
    private static HttpClient client;
    public static final int CONNECTION_TIMEOUT = 200000;
    public static final int SO_TIMEOUT = 20000;

    private HttpGetUtil() {
    }

    public static HttpGetUtil getClient() {
        if (client == null) {
            client = new DefaultHttpClient();
            // 请求超时
            client.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, CONNECTION_TIMEOUT);
            // 读取超时
            client.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, SO_TIMEOUT);
        }
        return new HttpGetUtil();
    }

    public static String getJson(String url) {
        String strResult = "";
        HttpGet httpGet = new HttpGet(url);
        try {
            HttpResponse response = client.execute(httpGet);
            if (response.getStatusLine().getStatusCode() == 200) {
                strResult = EntityUtils.toString(response.getEntity());
                return strResult;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}
